package com.xuecheng.content.service.impl;

import com.alibaba.fastjson.JSON;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.config.MultipartSupportConfig;
import com.xuecheng.content.feignclient.MediaServiceClient;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.mapper.CoursePublishMapper;
import com.xuecheng.content.mapper.CoursePublishPreMapper;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.CoursePreviewDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.content.model.po.CoursePublishPre;
import com.xuecheng.content.service.CourseBaseInfoService;
import com.xuecheng.content.service.CoursePublishService;
import com.xuecheng.content.service.TeachplanService;
import com.xuecheng.messagesdk.model.po.MqMessage;
import com.xuecheng.messagesdk.service.MqMessageService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 课程发布相关接口实现
 */
@Slf4j
@Service
public class CoursePublishServiceImpl implements CoursePublishService {

    @Autowired
    CourseBaseInfoService courseBaseInfoService;

    @Autowired
    TeachplanService teachplanService;

    @Autowired
    CourseBaseMapper courseBaseMapper;

    @Autowired
    CourseMarketMapper courseMarketMapper;

    @Autowired
    CoursePublishPreMapper coursePublishPreMapper;

    @Autowired
    CoursePublishMapper coursePublishMapper;

    @Autowired
    MqMessageService mqMessageService;

    @Autowired
    MediaServiceClient mediaServiceClient;

//    @Autowired
//    RedisTemplate redisTemplate;
//
//    @Autowired
//    RedissonClient redissonClient;

    @Override
    public CoursePreviewDto getCoursePreviewInfo(Long courseId) {

        CoursePreviewDto coursePreviewDto = new CoursePreviewDto();
        //课程基本信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        //课程计划信息
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);
        coursePreviewDto.setCourseBase(courseBaseInfo);
        coursePreviewDto.setTeachplans(teachplanTree);

        return coursePreviewDto;
    }

    @Transactional
    @Override
    public void commitAudit(Long companyId, Long courseId) {

        //查询课程基本信息
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        //查询课程营销信息
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);
        //查询课程基本信息、课程营销信息
        CourseBaseInfoDto courseBaseInfo = courseBaseInfoService.getCourseBaseInfo(courseId);
        //查询课程计划
        List<TeachplanDto> teachplanTree = teachplanService.findTeachplanTree(courseId);

        //1.约束
        String auditStatus = courseBaseInfo.getAuditStatus();
        //1.1审核完毕后，才可重新提交审核
        if ("202003".equals(auditStatus)) {
            XueChengPlusException.cast("该课程目前处于审核状态，需等待审核完毕方可重新提交");
        }
        //1.2本机构只允许提交本机构的课程
        if (!companyId.equals(courseBaseInfo.getCompanyId())) {
            XueChengPlusException.cast("本机构只允许提交本机构的课程");
        }
        //1.3没有上传图片，不允许提交
        if (StringUtils.isEmpty(courseBaseInfo.getPic())) {
            XueChengPlusException.cast("没有上传课程封面，不允许提交审核");
        }
        //1.4没有添加课程计划，不允许提交
        if (teachplanTree == null || teachplanTree.size() == 0) {
            XueChengPlusException.cast("没有添加课程计划，不允许提交审核");
        }
        //2.封装数据到课程预提交对象中
        CoursePublishPre coursePublishPre = new CoursePublishPre();
        BeanUtils.copyProperties(courseBaseInfo, coursePublishPre);
        coursePublishPre.setMarket(JSON.toJSONString(courseMarket));
        coursePublishPre.setTeachplan(JSON.toJSONString(teachplanTree));
        coursePublishPre.setCompanyId(companyId);
        coursePublishPre.setCreateDate(LocalDateTime.now());
        //3.设置预发布记录为已提交
        coursePublishPre.setStatus("202003");
        //判断是否存在课程预发布记录，若存在则更新，不存在则插入
        CoursePublishPre coursePublishPreUpdate = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPreUpdate == null) {
            //不存在，插入即可
            coursePublishPreMapper.insert(coursePublishPre);
        } else {
            //存在，需要更新
            coursePublishPreMapper.updateById(coursePublishPre);
        }
        //将课程基本信息修改为已提交
        courseBase.setAuditStatus("202003");
        courseBaseMapper.updateById(courseBase);
    }

    @Transactional
    @Override
    public void publish(Long companyId, Long courseId) {

        //查询预发布表
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null) {
            XueChengPlusException.cast("请先提交课程审核，审核通过后方可发布");
        }
        //状态
        if (!"202004".equals(coursePublishPre.getStatus())) {
            XueChengPlusException.cast("课程没有审核通过，不允许发布");
        }
        if (!coursePublishPre.getCompanyId().equals(companyId)) {
            XueChengPlusException.cast("操作失败，本机构只允许发布本机构的课程");
        }
        //向课程发布表中保存数据
        saveCoursePublish(courseId);
        //向消息表中插入数据
        saveCoursePublishMessage(courseId);
        //删除课程预发布表中的对应记录
        coursePublishPreMapper.deleteById(courseId);
    }

    @Override
    public File generateCourseHtml(long courseId) {

        Configuration configuration = new Configuration(Configuration.getVersion());
        //最终的静态文件
        File htmlFile = null;
        try {
            //拿到classpath路径
            String classpath = this.getClass().getResource("/").getPath();
            //指定模板的目录
            configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
            //指定编码
            configuration.setDefaultEncoding("utf-8");

            //得到模板
            Template template = configuration.getTemplate("course_template.ftl");
            //准备数据
            CoursePreviewDto coursePreviewInfo = this.getCoursePreviewInfo(courseId);
            HashMap<String, Object> map = new HashMap<>();
            map.put("model", coursePreviewInfo);

            //Template template 模板, Object model 数据
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            //输入流
            InputStream inputStream = IOUtils.toInputStream(html, "utf-8");
            htmlFile = File.createTempFile("coursepublish", ".html");
            //输出文件
            FileOutputStream outputStream = new FileOutputStream(htmlFile);
            //使用流将html写入文件
            IOUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error("页面静态化出现问题，课程id:{}", courseId, e);
            e.printStackTrace();
        }
        return htmlFile;
    }

    @Override
    public void uploadCourseHtml(Long courseId, File file) {

        try {
            //将file转成MultipartFile
            MultipartFile multipartFile = MultipartSupportConfig.getMultipartFile(file);
            //远程调用得到返回值
            String upload = mediaServiceClient.upload(multipartFile, "course/" + courseId + ".html");
            if (upload == null) {
                log.debug("远程调用走降级策略得到上传结果为null,课程id:{}", courseId);
                XueChengPlusException.cast("上传静态文件过程中存在异常");
            }
        } catch (IOException e) {
            e.printStackTrace();
            XueChengPlusException.cast("上传静态文件过程中存在异常");
        }
    }

    /**
     * 根据课程id查询课程发布信息
     *
     * @param courseId 课程id
     * @return
     */
    @Override
    public CoursePublish getCoursePublish(Long courseId) {
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        return coursePublish;
    }

    //解决缓存穿透
//    @Override
//    public CoursePublish getCoursePublishCache(Long courseId) {
//
//        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
//        //缓存中有
//        if (jsonObj != null) {
//            //缓存中有直接返回数据
//            String jsonString = jsonObj.toString();
//            if ("null".equals(jsonString)){
//                return null;
//            }
//            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
//            return coursePublish;
//        }else {
//            //从数据库查询
//            CoursePublish coursePublish = getCoursePublish(courseId);
////            if (coursePublish != null) {
//                //查询完再存储到redis,无论是否为null都缓存，防止缓存穿透
//                redisTemplate.opsForValue().set("course:"+courseId,JSON.toJSONString(coursePublish),30, TimeUnit.SECONDS);
////            }
//            return coursePublish;
//        }
//    }

    //使用同步锁解决缓存击穿
//    @Override
//    public CoursePublish getCoursePublishCache(Long courseId) {
//
//
//            //从缓存中查询
//            Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
//            //缓存中有
//            if(jsonObj!=null){
////            System.out.println("=============从缓存中查询=============");
//                //缓存中有直接返回数据
//                String jsonString = jsonObj.toString();
//                if("null".equals(jsonString)){
//                    return null;
//                }
//                CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
//                return coursePublish;
//            }else{
//                synchronized (this){
//                    //再次查询一下缓存
//                    //从缓存中查询
//                    jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
//                    //缓存中有
//                    if(jsonObj!=null) {
//                        //缓存中有直接返回数据
//                        String jsonString = jsonObj.toString();
//                        if("null".equals(jsonString)){
//                            return null;
//                        }
//                        CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
//                        return coursePublish;
//                    }
//                    System.out.println("==查询数据库==");
//                    //从数据库查询
//                    CoursePublish coursePublish = getCoursePublish(courseId);
//                    //查询完成再存储到redis
//                    redisTemplate.opsForValue().set("course:"+courseId,JSON.toJSONString(coursePublish),300, TimeUnit.SECONDS);
//                    return coursePublish;
//
//                }
//
//
//
//            }

    //使用redisson实现分布式锁
//    @Override
//    public CoursePublish getCoursePublishCache(Long courseId) {
//
//
//        //从缓存中查询
//        Object jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
//        //缓存中有
//        if (jsonObj != null) {
////            System.out.println("=============从缓存中查询=============");
//            //缓存中有直接返回数据
//            String jsonString = jsonObj.toString();
//            if ("null".equals(jsonString)) {
//                return null;
//            }
//            CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
//            return coursePublish;
//        } else {
//            RLock lock = redissonClient.getLock("coursequerylock:" + courseId);
//            //获取分布式锁
//            lock.lock();
//            try {
//                //再次查询一下缓存
//                //从缓存中查询
//                jsonObj = redisTemplate.opsForValue().get("course:" + courseId);
//                //缓存中有
//                if (jsonObj != null) {
//                    //缓存中有直接返回数据
//                    String jsonString = jsonObj.toString();
//                    if ("null".equals(jsonString)) {
//                        return null;
//                    }
//                    CoursePublish coursePublish = JSON.parseObject(jsonString, CoursePublish.class);
//                    return coursePublish;
//                }
//                System.out.println("==查询数据库==");
////                try {
////                    //手动延迟，测试锁的续期功能
////                    Thread.sleep(60000);
////                } catch (InterruptedException e) {
////                    throw new RuntimeException(e);
////                }
//                //从数据库查询
//                CoursePublish coursePublish = getCoursePublish(courseId);
//                //查询完成再存储到redis
//                redisTemplate.opsForValue().set("course:" + courseId, JSON.toJSONString(coursePublish), 300, TimeUnit.SECONDS);
//                return coursePublish;
//
//            } finally {
//                //手动释放锁
//                lock.unlock();
//            }
//        }
//
//
//    }

    //分布式锁原理 redis的setnx实现
    //下述代码10~13行非原子性，也会导致删除其他线程的锁
    //想实现原子性，需要让redis去执行Lua脚本的方式去实现，这样就具有原子性，但是过期时间的值设置还存在不精准的问题
//    if (缓存中有) {
//        返回缓存中的数据
//    } else {
//        获取分布式锁:
//        set lock 01 NX
//        if (获取锁成功）{
//            try {
//                查询数据库
//            } finally {
//                if (redis.call("get", "lock") == "01") {
//                    释放锁:
//                    redis.call("del", "lock")
//                }
//            }
//        }
//    }

    /**
     * 保存课程发布信息
     *
     * @param courseId 课程id
     */
    private void saveCoursePublish(Long courseId) {
        CoursePublishPre coursePublishPre = coursePublishPreMapper.selectById(courseId);
        if (coursePublishPre == null) {
            XueChengPlusException.cast("课程预发布信息为空");
        }
        CoursePublish coursePublish = new CoursePublish();
        BeanUtils.copyProperties(coursePublishPre, coursePublish);
        //设置发布状态为已发布
        coursePublish.setStatus("203002");
        //判断在课程发布表中是否已存在，存在则更新，不存在则插入
        CoursePublish coursePublishUpdate = coursePublishMapper.selectById(courseId);
        if (coursePublishUpdate == null) {
            //不存在，插入
            coursePublishMapper.insert(coursePublish);
        } else {
            //存在，更新
            coursePublishMapper.updateById(coursePublish);
        }
        //将课程基本信息表更新为已发布
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        courseBase.setAuditStatus("203002");
        courseBaseMapper.updateById(courseBase);
    }

    /**
     * 保存消息表
     *
     * @param courseId 课程id
     */
    private void saveCoursePublishMessage(Long courseId) {
        MqMessage mqMessage = mqMessageService.addMessage("course_publish", String.valueOf(courseId), null, null);
        if (mqMessage == null) {
            XueChengPlusException.cast(CommonError.UNKOWN_ERROR);
        }
    }
}
